package com.egao.gps.mongo;

import com.mongodb.client.*;
import org.bson.Document;

import java.util.function.Consumer;

/**
 * @author Damon
 * @create 2020-11-17 12:04
 */
public class MongoDemo {

    public static void main(String[] args) {

//        MongoCredential credential = MongoCredential.createCredential("用户名", "数据库名称", "密码".toCharArray());
//        MongoClient mongoClient = new MongoClient(new ServerAddress("127.0.0.1", 27017), Arrays.asList(credential));
        //1.创建链接
        MongoClient client = MongoClients.create("mongodb://127.0.0.1:27017");
        //2.打开数据库test
        MongoDatabase db = client.getDatabase("itying");
        //3.获取集合
        MongoCollection<Document> collection = db.getCollection("admin");
        //4.查询获取文档集合
        FindIterable<Document> documents = collection.find();
        //5.循环遍历
        for (Document document : documents) {
            System.out.println(document);
        }

        collection.find().limit(5).forEach((Consumer<? super Document>) document -> {
            System.out.println(document.toJson());
        });
        //6.关闭连接
        client.close();

    }
}
